package cn.cubix.flow.security;

import cn.cubix.flow.util.ResponseUtil;
import cn.cubix.flow.util.Result;
import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class AuthEventHandler implements AccessDeniedHandler, AuthenticationEntryPoint {

    /**
     * 已登录用户访问无权限资源
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        log.warn("[{}]请求访问[{}]，无权限",request.getRemoteAddr(),request.getRequestURI());
        ResponseUtil.writeResponse(response, HttpStatus.HTTP_FORBIDDEN,
                Result.FAILURE()
                        .setCode("NO_PERMISSION")
                        .setMessage("无权限")
                        .setException(e)
                        .toJSONObject()
        );
    }

    /**
     * 登录失败、未登录访问无权限资源
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        if(e instanceof BadCredentialsException||e instanceof InternalAuthenticationServiceException){
            log.warn("[{}]登录失败",request.getRemoteAddr());
            ResponseUtil.writeResponse(response, HttpStatus.HTTP_UNAUTHORIZED,
                    Result.FAILURE()
                            .setCode("LOGIN_FAILURE")
                            .setMessage("登录失败")
                            .setException(e)
                            .toJSONObject()
            );
            return;
        }
        // 登录过期 没有token、无效的token
        log.warn("[{}]请求访问[{}]，登录过期",request.getRemoteAddr(),request.getRequestURI());
        ResponseUtil.writeResponse(
                response,HttpStatus.HTTP_UNAUTHORIZED,
                Result.FAILURE()
                        .setCode("LOGIN_TIMEOUT")
                        .setMessage("登录状态过期")
                        .setException(e).toJSONObject()
        );
    }
}
